#include "InetAddress.h"

#include "SocketUtils.h"
#include "../../base/Types.h"

#include <cstring>
#include <arpa/inet.h>

InetAddress::InetAddress(int port) {
    memZero(&addr_, sizeof addr_);
    addr_.sin_family = AF_INET;
    addr_.sin_addr.s_addr = htonl(INADDR_ANY);
    addr_.sin_port = htons(port);
}

InetAddress::InetAddress(std::string ip, int port) {
    memZero(&addr_, sizeof addr_);
    addr_.sin_family = AF_INET;
    inet_pton(AF_INET, ip.c_str(), &addr_.sin_addr.s_addr);
    addr_.sin_port = htons(port);
}

std::string InetAddress::toIp() const {
    /*char IP[BUFSIZ];
    inet_ntop(AF_INET, &addr_.sin_addr.s_addr, IP, sizeof(IP));
    return std::string(IP);*/
    char buf[64] = "";
    sockets::toIp(buf, sizeof buf, getSockAddr());
    return buf;
}

int InetAddress::toPort() const {
    return ntohs(addr_.sin_port);
}

std::string InetAddress::toIpPort() const {
    char buf[64] = "";
    sockets::toIpPort(buf, sizeof buf, getSockAddr());
    return buf;
}

